package com.cszy.yydqbfq.common

import com.cszy.yydqbfq.bean.AudioItemBean
import com.cszy.yydqbfq.bean.Song
import com.cszy.yydqbfq.bean.SongListBean
import org.litepal.LitePal

class PlaylistRepository {
    private val playlists = mutableListOf<SongListBean>()


    init {

        // 确保本地歌单存在
        if (LitePal.where("isLocal = ?", "1").find(SongListBean::class.java).isEmpty()) {
            val localPlaylist = SongListBean(
                name = "本地音乐",
                cover = "local_music_cover",
                isLocal = true,
                createTime = 0L,
                localCount = 0
            ).save()


        }
    }

    fun getAllPlaylists(): List<SongListBean> {
        return LitePal.order("isLocal desc, createTime desc").find(SongListBean::class.java)
    }

    fun addPlaylist(name: String, cover: String): Boolean {
        return SongListBean(
            name = name,
            cover = cover,
            isLocal = false,
            createTime = System.currentTimeMillis()
        ).save()
    }


    /**
     * 编辑歌单信息
     */
    fun updatePlaylist(playlistId: Long, name: String, cover: String): Boolean {
        val playlist = LitePal.find(SongListBean::class.java, playlistId)
        return playlist?.let {
            it.name = name
            it.cover = cover
            it.save()
        } ?: false
    }

    fun deletePlaylist(id: Long): Boolean {
        // 先删除关联的歌曲（使用正确的外键名）
        LitePal.deleteAll(Song::class.java, "songlistbean_id = ?", id.toString())
        // 再删除歌单
        return LitePal.delete(SongListBean::class.java, id) > 0
    }

    fun getPlaylistById(id: Long): SongListBean? {
        return LitePal.find(SongListBean::class.java, id)
    }

    fun addSongToPlaylist(playlistId: Long, song: Song): Boolean {
        if (isSongExistsInPlaylist(playlistId, song.title, song.artist)) {
            return false
        }
        song.songlistbean_id = playlistId
        return song.save()
    }

    /**
     * 检查歌曲是否已存在于指定歌单中
     */
    fun isSongExistsInPlaylist(playlistId: Long, title: String, artist: String): Boolean {
        return LitePal.where("songlistbean_id = ? and title = ? and artist = ?",
            playlistId.toString(), title, artist)
            .count(Song::class.java) > 0
    }

    fun removeSongFromPlaylist(songId: Long): Boolean {
        return LitePal.delete(Song::class.java, songId) > 0
    }


}
